package cn.shengongying.api.controller;

import cn.shengongying.anon.Ignore;
import cn.shengongying.anon.User;
import cn.shengongying.api.dto.*;
import cn.shengongying.api.vo.BossPositionDetailVo;
import cn.shengongying.api.vo.PositionListVo;
import cn.shengongying.api.vo.PositionVo;
import cn.shengongying.api.vo.UserInterviewVo;
import cn.shengongying.bean.BaseUser;
import cn.shengongying.bean.ResponseResult;
import cn.shengongying.enums.MsgEnum;
import cn.shengongying.enums.PositionStatusEnum;
import cn.shengongying.enums.ResponseCodeEnum;
import cn.shengongying.model.*;
import cn.shengongying.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * author: RXK
 * date: 2022/1/7 星期五
 * desc:
 */
@RestController
@Api(tags = "职位管理")
@RequestMapping("/boss/position")
public class BossPositionController extends BaseController {

    private final IWorkerListService workerListService;

    private final IInformationService informationService;

    private final IBossPositionService bossPositionService;

    private final IBossCompanyInfoService companyInfoService;


    private final IUserPositionApplyRecordService positionApplyRecordService;


    public BossPositionController(IWorkerListService workerListService, IInformationService informationService, IBossCompanyInfoService companyInfoService, IBossPositionService bossPositionService, IUserPositionApplyRecordService positionApplyRecordService) {
        this.workerListService = workerListService;
        this.informationService = informationService;
        this.companyInfoService = companyInfoService;
        this.bossPositionService = bossPositionService;
        this.positionApplyRecordService = positionApplyRecordService;
    }

    @Ignore
    @ApiOperation(value = "职位搜索")
    @PostMapping("/search")
    public ResponseResult<String> search() {
        return ResponseResult.success();
    }


    @PostMapping("/list")
    @ApiOperation(value = "职位管理列表")
    public ResponseResult<List<PositionVo>> list(@ApiIgnore @User BaseUser baseUser) {
        List<BossPosition> templateList = bossPositionService.findByBossId(baseUser.getId(), 0);
        List<PositionVo> voList = BossPositionDetailVo.positionList(templateList);
        return ResponseResult.success(voList);
    }

    @Ignore
    @ApiOperation(value = "职位招聘列表")
    @PostMapping(value = "/recruitment/list")
    public ResponseResult<List<PositionListVo>> recruitmentList(@ApiIgnore @User BaseUser baseUser) {
        List<BossPosition> templateList = bossPositionService.findByBossId(baseUser.getId(), 1);
        List<PositionListVo> voList = BossPositionDetailVo.recruitmentList(templateList);
        return ResponseResult.success(voList);
    }


    @Ignore
    @ApiOperation(value = "详情")
    @PostMapping("/detail")
    public ResponseResult<BossPositionDetailVo> detail(@RequestBody @Validated IdInDTO inDTO) {
        BossPosition positionTemplate = bossPositionService.getById(inDTO.getId());
        Assert.notNull(positionTemplate, ResponseCodeEnum.param_exception.getMsg());
        BossPositionDetailVo vo = BossPositionDetailVo.detail(positionTemplate);
        return ResponseResult.success(vo);
    }


    @ApiOperation(value = "新增职位/编辑职位")
    @PostMapping("/update")
    public ResponseResult<String> management(@ApiIgnore @User BaseUser baseUser, @RequestBody @Validated PositionInDTO inDTO) {
        inDTO.checkParams();
        BossPosition template = inDTO.build(baseUser);
        bossPositionService.saveOrUpdate(template);
        BossCompanyInfo companyInfo = inDTO.buildCompany(baseUser);
        companyInfoService.create(companyInfo);
        return ResponseResult.success();
    }


    @ApiOperation(value = "删除职位")
    @PostMapping("/delete")
    public ResponseResult<String> delete(@RequestBody @Validated IdInDTO inDTO) {
        bossPositionService.updateStatusById(inDTO.getId(), PositionStatusEnum.delete.ordinal());
        return ResponseResult.success();
    }

    @ApiOperation(value = "置顶")
    @PostMapping("/top")
    public ResponseResult<String> top(@RequestBody @Validated PositionTopStatusInDTO inDTO) {
        bossPositionService.updateTopStatus(inDTO.getId(), inDTO.getTopStatus());
        return ResponseResult.success();
    }


    @ApiOperation(value = "申请列表、面试列表、职列表")
    @PostMapping("/apply/list")
    public ResponseResult<List<UserInterviewVo>> applyList(@ApiIgnore @User BaseUser baseUser, @RequestBody @Validated PositionApplyInDTO inDTO) {
        List<UserPositionApplyRecord> recordList = positionApplyRecordService.findByBossIdAndPositionIdPage(baseUser.getId(), inDTO.getId(), inDTO.getType());
        List<Long> userIds = recordList.stream()
                .map(UserPositionApplyRecord::getUserId)
                .collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(userIds)) {
            List<WorkerList> lists = workerListService.findByUserIds(userIds);
            List<UserInterviewVo> voList = UserInterviewVo.list(recordList, lists);
            return ResponseResult.success(voList);
        }
        return ResponseResult.success(Collections.emptyList());
    }


    @ApiOperation(value = "附近的用户")
    @PostMapping("/nearby/user")
    public ResponseResult<List<UserInterviewVo>> nearbyUsers(@RequestBody @Validated WorkerSearchInDTO inDTO) {

        return ResponseResult.success();
    }

    @ApiOperation(value = "用户是否被邀请过")
    @PostMapping("/interview/checked")
    public ResponseResult<String> userInterviewed(@RequestBody @Validated UserInterviewInDTO inDTO) {
        int count = informationService.findByUserIdAndSourceIdAndDate(inDTO.getUserId(), inDTO.getId(), 4);
        if (count == 0) {
            return ResponseResult.success();
        } else {
            return ResponseResult.fail();
        }
    }


    /**
     * 附近面试邀请 (不包含日期)
     * 申请列表面试邀请(包含日期)
     */
    @ApiOperation(value = "邀请面试")
    @PostMapping(value = "/invite/interview")
    public ResponseResult<String> inviteInterView(@ApiIgnore @User BaseUser baseUser, @RequestBody @Validated PositionInviteInterviewInDTO inDTO) {
        BossPosition position = bossPositionService.getById(inDTO.getId());
        Assert.notNull(position, ResponseCodeEnum.param_exception.getMsg());
        //校验用户 是否有对应类型的简历发布
        Set<Long> userId = inDTO.userId();
        int count = workerListService.countByUserIdAndType(userId, position.getType());
        if (count != userId.size()) {
            return ResponseResult.fail(ResponseCodeEnum.user_no_worker_exception);
        }
        List<Information> informationList;
        switch (inDTO.getType()) {
            case 0:
                informationList = inDTO.buildMsg(baseUser, position);
                informationService.save(informationList);
                break;
            case 1:
                Assert.notNull(inDTO.getResumeDate(), ResponseCodeEnum.param_exception.getMsg());
                List<UserPositionApplyRecord> recordList = positionApplyRecordService.userApplyRecord(inDTO.getUserId(), position.getId(), 0);
                if (CollectionUtils.isNotEmpty(recordList)) {
                    recordList = inDTO.buildApplyRecord(recordList);
                    informationList = inDTO.buildInterviewMsg(baseUser, position);
                    informationService.saveBatch(informationList);
                    positionApplyRecordService.updateBatchById(recordList);
                }
                break;
            default:
                return ResponseResult.fail();
        }
        return ResponseResult.success();
    }


    @ApiOperation(value = "确认招满/下架职位")
    @PostMapping(value = "/full")
    public ResponseResult<String> full(@ApiIgnore @User BaseUser baseUser, @RequestBody @Validated IdInDTO inDTO) {
        BossPosition position = bossPositionService.getById(inDTO.getId());
        //是否有待确认入职 但还没有入职的用户
        List<UserPositionApplyRecord> recordList = positionApplyRecordService.findByPositionIdAndStatus(inDTO.getId(), 1);
        if (CollectionUtils.isNotEmpty(recordList)) {
            List<Information> informationList = recordList.stream()
                    .map(userPositionApplyRecord -> {
                        Information information = new Information();
                        information.setContent(String.format(MsgEnum.position_full_msg.getMsg(), position.getCompanyName(), position.getPositionName()));
                        information.setType(5);
                        information.setUserId(userPositionApplyRecord.getUserId());
                        information.setSourceId(position.getId());
                        information.setFrom(baseUser.getId());
                        information.setRead(0);
                        return information;
                    })
                    .collect(Collectors.toList());
            informationService.saveBatch(informationList);
        }
        bossPositionService.updateStatusById(inDTO.getId(), PositionStatusEnum.full_man_down.ordinal());

        //再copy一个新的招聘职位
        position.setId(null);
        position.setTopStatus(0);
        position.setStatus(PositionStatusEnum.normal.ordinal());
        position.setMemberNumber(0);
        position.setApplyNumber(0);
        bossPositionService.save(position);
        return ResponseResult.success();
    }

}
